import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useNodesStore = defineStore('notesStore', () => {
  const notes = ref([
    {
      id: 100,
      content: '我学会了Vuex的三个重要组成部门：state(getters), mutations, actions'
    },
    {
      id: 200,
      content: 'getters如何传参——在getters函数里返回一个函数，这个函数是可以接收组件传递过来的参数的。'
    },
  ])

  const msg = ref('abc')

  const add = (note) => {
    notes.value.unshift(note)
  }

  const changeMsg = () => {
    msg = 'aaabbbccc'
  }
  
  const deleteNote = (id) => {
    // 方法一：
    // const newNotes = notes.value.filter(note => note.id !== id)
    // notes = newNotes

    // 方法二：
    const index = notes.value.findIndex(note => note.id === parseInt(id))
    notes.value.splice(index, 1)
  }

  const saveNote = (payload) => {
    const { id, note } = payload
    const obj = notes.value.find(n => n.id === parseInt(id))
    obj.content = note
  }

  const contentById = (id) => {
    return computed(() => {
      const note = notes.value.find(note => note.id === parseInt(id))
      return note.content
    })
  }

  const itemsCount = computed(() => {
    return notes.value.length
  })

  const charactorCount = computed(() => {
    return notes.value.reduce((sum, note) => {
      sum += note.content.length
      return sum
    }, 0)
  })


  return {
    notes,
    msg,
    add,
    changeMsg,
    deleteNote,
    saveNote,
    contentById,
    itemsCount,
    charactorCount
  }
})